package com.itheima.search.controller;

import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.search.document.ArticleInfoDocument;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.service.ApUserSearchService;
import com.itheima.search.service.ArticleInfoDocumentSearchService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.search
 */
@RestController
@RequestMapping("/article/search")
public class SearchController {

    @Resource
    private ArticleInfoDocumentSearchService articleInfoDocumentSearchService;

    @Resource
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索功能
     * @param dto
     * @return
     */
    @PostMapping("/search")
    public ResultVo<List<ArticleInfoDocument>> search(@RequestBody SearchDto dto){
        List<ArticleInfoDocument> list = articleInfoDocumentSearchService.search(dto);
        // 请求对象是绑定搜索当前线程，登录用户的id只能在这个线程的代码中来获取
        Long loginUserId = RequestContextUtil.getUserId();
        if(!StringUtils.isEmpty(dto.getSearchWords())){
            // 有关键字才需要保存, 开启另一个异步线程,因此它获取不到登录用户id
            apUserSearchService.saveSearchWords(loginUserId,dto.getSearchWords());
        }
        return ResultVo.ok(list);
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            add2List(list,i+"");
        }
        list.forEach(System.out::println);
        System.out.println("=====================");
        add2List(list, "11");
        list.forEach(System.out::println);
        System.out.println("=====================");
        add2List(list, "8");
        list.forEach(System.out::println);
    }

    private static void add2List(List<String> list, String s) {

        // 判断集合中是否包含值
        int index = list.indexOf(s);
        if(index==0){
            return;
        }else if (index > 0){
            // 存在
            list.remove(index);
        }
        int size = list.size();
        if(size == 10){
            list.remove(size-1);
        }

        list.add(0,s);
    }
}
